// src/utils/eventBus.ts
import mitt, { Emitter } from 'mitt'

// 定义事件类型
type Events = {
  // 基础事件格式
  'cancel-tabbar-event': void
  'add-tabbar-event': void
  // 带参数的事件
  'update-cart': { id: number; count: number }

  // 支付相关事件
  'payment-success': { orderId: string }
  'payment-failed': { code: number; msg: string }
}

// 创建单例模式
class EventBus {
  private static instance: Emitter<Events>

  static getInstance(): Emitter<Events> {
    if (!EventBus.instance) {
      EventBus.instance = mitt<Events>()
    }
    return EventBus.instance
  }
}

// 导出常用方法
export const emitter = EventBus.getInstance()

// 导出类型化的方法
export const useEventBus = () => {
  return {
    emitts: <T extends keyof Events>(event: T, payload?: Events[T]) => {
      emitter.emit(event, payload)
    },
    on: <T extends keyof Events>(event: T, handler: (payload: Events[T]) => void) => {
      emitter.on(event, handler as any)
      return () => emitter.off(event, handler as any)
    },
    off: <T extends keyof Events>(event: T, handler?: (payload: Events[T]) => void) => {
      emitter.off(event, handler as any)
    },
  }
}
